export type PracticeItem = {
  name: string;
  markdown?: string;
  path: string;
  icon?: string;
  title: string;
  children: Array<PracticeItem>;
};

const removeExtension = (filePath: string): string => {
  return filePath.replace(/\.[^/.]+$/, "");
};

const LoadVues = () => {
  let practices: PracticeItem = {
    name: "/",
    path: "/",
    title: "root",
    children: []
  };
  const vues = import.meta.glob([
    "@/views/**/*.vue",
    "!@/views/**/components/*.vue",
    "!@/views/Home.vue"
  ]);
  // 对 vues 的键进行排序
  //   const sortedVues = Object.keys(vues).sort((a, b) => a.localeCompare(b)); // 使用 localeCompare 进行排序
  //   console.log(vues);
  for (const v in vues) {
    const parts = removeExtension(v).split("/").filter(Boolean).slice(2);
    let currentLevel = practices;
    parts.forEach((part, index) => {
      if (index < parts.length - 1) {
        const item = currentLevel.children.find(child => child.name == part);
        if (item) {
          currentLevel = item;
        } else {
          const newNode: PracticeItem = {
            name: part,
            title: part,
            path: part,
            children: []
          };
          currentLevel.children.push(newNode);
          currentLevel = newNode;
        }
      }
      if (index === parts.length - 1) {
        const newNode: PracticeItem = {
          name: part,
          title: part,
          path: v,
          children: []
        };
        currentLevel.children.push(newNode);
      }
    });
  }
  return practices;
};

const LoadSvgs = (practices: PracticeItem) => {
  const svgs = import.meta.glob(["@/views/**/*.svg"]);
  for (const v in svgs) {
    const parts = removeExtension(v).split("/").filter(Boolean).slice(2);
    let currentLevel = practices;
    parts.forEach((part, index) => {
      const item = currentLevel.children.find(child => child.name == part);
      if (item) {
        currentLevel = item;
      } else {
        return;
      }
      if (index === parts.length - 1 && currentLevel.name == part) {
        currentLevel.icon = v;
      }
    });
  }
};
const LoadMds = (practices: PracticeItem) => {
  const mds = import.meta.glob(["@/views/**/*.md"]);
  for (const v in mds) {
    const parts = removeExtension(v).split("/").filter(Boolean).slice(2);
    let currentLevel = practices;
    parts.forEach((part, index) => {
      const item = currentLevel.children.find(child => child.name == part);
      if (item) {
        currentLevel = item;
      } else {
        return;
      }
      if (index === parts.length - 1 && currentLevel.name == part) {
        currentLevel.markdown = v;
      }
    });
  }
};

const LoadItems = () => {
  const vues = LoadVues();
  // console.log(vues);
  LoadSvgs(vues);
  LoadMds(vues);
  return vues;
};

export const generateMenu = () => {
  return LoadItems();
};
